package com.platform.comm.validation;

import com.platform.comm.validation.constraints.Candidates;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 字符串候选值Validator<br>
 * 判断其是否在预定义的候选值当中
 * @author tommy
 */
public class CandidatesValidator implements ConstraintValidator<Candidates, String> {

    private boolean nullable = true;

    private final List<String> candidates = new ArrayList<>();

    @Override
    public void initialize(Candidates constraintAnnotation) {
        nullable = constraintAnnotation.nullable();
        candidates.addAll(Arrays.asList(constraintAnnotation.value()));
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return nullable;
        }
        return candidates.contains(value);
    }
}
